package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired(required = false)
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {

        R<Employee> r = employeeService.login(employee);
        if (r.getCode() == 1) {
            session.setAttribute("employee", r.getData().getId());
        }
        return r;
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession session) {
        Long id = (Long) session.getAttribute("employee");
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        Boolean flag = employeeService.save(employee);
        if (flag) {
            return R.success("添加成功");
        }
        return R.error("添加失败");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(Integer page, Integer pageSize, String name) {
        Page<Employee> pagedata = employeeService.findByPage(page, pageSize, name);
        if (pagedata == null) {
            return R.error("查询失败");
        }
        return R.success(pagedata);
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Integer id){
        System.out.println(id);
        R<Employee> r = employeeService.findById(id);
        return r;
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){
        Long id = (Long)session.getAttribute("employee");
        employee.setUpdateUser(id);
        employeeService.update(employee);
        return R.success("修改成功");
    }
}
